<template>
  <div class="spl-container">
    <breadcrumb :data="pathData"></breadcrumb>
    <div class="user-container">
      <div class="search-row m-form">
        <el-input placeholder="搜索用户名称/手机/邮箱" class="ml-20 w-220" v-model="searchWord"></el-input>
        <el-button type="primary" class="search-btn" icon="el-icon-search" @click="getTableData"></el-button>

        <div class="search-row-btn">
          <el-button type="primary" class="opt-btn green-btn" icon="el-icon-circle-plus-outline" @click="addUser">新增用户
          </el-button>
        </div>
      </div>

      <dTable @fetch="getTableData" ref="userTable" :tableHeight="tableHeight" :showIndex="true">
        <el-table-column prop="userName" label="用户名称" width="130px" header-align="center" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否启用" width="130px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.active" @change="userActiveChange(scope.row)" :activeColor="$global.switchColor[0]"
                       :inactiveColor="$global.switchColor[1]" :active-value="true" :inactive-value="false">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号码" width="150px" header-align="center" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="email" label="用户邮箱" width="160px" header-align="center" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="roles" label="用户角色" min-width="200px" header-align="center" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.roles | parseRoles}}
          </template>
        </el-table-column>
        <el-table-column prop="organizations" label="用户所属组织" min-width="160px" header-align="center" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.organizations | parseOrganizations}}
          </template>
        </el-table-column>
        <el-table-column prop="approveTime" label="账号启用时间" min-width="160px" header-align="center" align="center"
                         :formatter="formatDateFunc" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column property="operation" width="130px" label="操作" header-align="center" align="center">
          <template slot-scope="scope">
            <el-dropdown split-button type="text" class="opt-btn opt-button">
              <span>管理</span>
              <el-dropdown-menu slot="dropdown">
                <router-link :to="'/usersinfo1?userId='+scope.row.id">
                  <el-dropdown-item icon="el-icon-setting">设置</el-dropdown-item>
                </router-link>
              </el-dropdown-menu>
            </el-dropdown>
          </template>

          <!--<el-button type="primary" size="mini" @click="gotoUserSetting">设置</el-button>-->
          <!--<el-button type="danger" size="mini" >注销</el-button>-->
        </el-table-column>
      </dTable>

      <el-dialog title="新增用户" class="spl-dialog addDialog" :visible.sync="dialogFormEditVisible" center
                 :closeOnClickModal="false" :before-close="clearAddField" width="700px">
        <el-form :model="ruleFormEdit" ref="ruleFormEdit" label-width="120px" class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="用户名称" prop="userName" :rules="[{ required: true, message: '请输入用户名称'}]">
                <el-input v-model="ruleFormEdit.userName" placeholder="1-50个字符" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="所属角色" prop="roleIds" :rules="[{ required: true, message: '请选择所属角色'}]">
                <el-select multiple v-model="ruleFormEdit.roleIds" placeholder="请选择" collapse-tags>
                  <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="手机号码" prop="mobile"
                            :rules="[{ required: true, message: '请输入手机号码'},{validator:this.validUserMobile,trigger:'blur'}]">
                <el-input v-model="ruleFormEdit.mobile" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="邮箱" prop="email" :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]">
                <el-input v-model="ruleFormEdit.email" type="text" placeholder="请输入"
                          autocomplete="new-password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="15">
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleFormEdit.password" :disabled="checked" placeholder="请输入" type="password"
                          autocomplete="new-password"></el-input>
              </el-form-item>

            </el-col>
            <el-col :span="9" class="mt-10">
              <el-checkbox v-model="checked" @change="setDefaultPassword" label="默认密码：6位随机数字+字符"></el-checkbox>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer operate-btns-bottom">
          <el-button @click="clearAddField">取 消</el-button>
          <el-button type="primary" :loading="addLoadingFlag" class="ml-30" @click="addUserMeagess">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import dTable from '../common/table'
  export default {
    components: {dTable},
    data() {
      return {
        pathData: [
          {name: '企业管理'},
          {name: '用户管理', path: '/usersinfo'}
        ],
        searchWord: '',
        dialogFormEditVisible: false,
        addLoadingFlag: false,
        checked: false,
        ruleFormEdit: {
          userName: '',
          roleIds: [],
          mobile: '',
          email: '',
          password: '',
          active: true
        },
        roles: []
      }
    },
    created() {
      this.getRoleOptions()
      this.$nextTick(() => {
        this.getTableData()
      })
    },
    computed: {
      tableHeight: function () {
        return this.$global.bodyHeight - 220 + 'px'
      }
    },
    filters: {
      parseRoles(value) {
        if (value && value.length > 0) {
          var roleNames = []
          value.forEach(item => {
            roleNames.push(item.roleName)
          })
          return roleNames.join(',')
        }
        return ''
      },
      parseOrganizations(value){
        if (value && value.length > 0) {
          var names = []
          value.forEach(item => {
            names.push(item.name)
          })
          return names.join(',')
        }
        return ''
      }

    },
    methods: {
      //获取用户可选角色的option项
      getRoleOptions() {
        this.$http({
          url: 'tenant/role/page',
          method: 'post',
          data: {
            filters: [{}],
            page: 1,
            query: [{}],
            sidx: '',
            size: 1000,
            sort: ''
          }
        }).then(({data}) => {
            let rows = data.rows;
            var res = [];
            for (let i = 0; i < rows.length; i++) {
                let row = rows[i];
                //00 代表启用  11代表未启用
                if (row.status=='00'){
                    res.push(row);
                }
            }
          this.roles = res;
        })
      },
      getTableData (params = []) {
        params = [{property: "userName_like", value: this.searchWord}]
        this.$refs.userTable.fetch(params, 'post', '/tenant/user/page')
      },
      //新增用户
      addUser (){
        this.dialogFormEditVisible = true
      },
      formatDateFunc(row, column, cellValue, index){
        return cellValue == null ? '-' : this.$global.dateToStrByFormart(cellValue, 'yyyy-MM-dd HH:mm:ss')
      },
      //  清除并关闭--新增字段
      clearAddField (done) {
        this.ruleFormEdit = {
          userName: '',
          roleIds: [],
          mobile: '',
          email: '',
          password: '',
          active: true
        }
        this.$refs.ruleFormEdit.resetFields()
        this.checked = false
        if (typeof done === 'function') {
          done()
        } else {
          this.dialogFormEditVisible = false
        }
      },
      setDefaultPassword(value){
        if (value) {
          this.ruleFormEdit.password = this.$global.generate('ps', 4)
        }
      },
      //新增用户
      addUserMeagess() {
        this.addLoadingFlag = true
        this.$refs['ruleFormEdit'].validate((valid) => {
          if (!valid) {
            this.addLoadingFlag = false
          } else {
            this.saveAdd()
          }
        })
      },
      saveAdd(){
        this.$http({
          url: 'tenant/user/add',
          method: 'post',
          data: this.ruleFormEdit
        }).then(({data}) => {
          this.addLoadingFlag = false
            if(data.code !==0) {
              return this.$message.error(data.msg);
          }
          this.dialogFormEditVisible = false
          this.checked = false
          this.getTableData()
        })
      },
      validUserMobile(rule, value, callback){
        if (value != undefined && value != null && value != '') {
          this.$http({
            url: '/sys/no-limit/validate/phone',
            method: 'post',
            data: {
              mobile: value,
              useType: '01'
            }
          }).then(({data}) => {
            if (data.code == -1) {
              if (!data.data) {
                callback(new Error(data.msg))
              } else {
                callback()
              }
            } else {
              callback()
            }
          })
        }
      },
      userActiveChange(user){
        this.$http({
          url: '/tenant/user/active',
          method: 'post',
          data: {
            id: user.id,
            active: user.active?'1':'0'
          }
        }).then(({data}) => {
          if (data.code === 0) {
            //this.$message.success(successMsg)
          } else {
            this.$message.error(this.$global.errorMsg)
          }
        })
      },
      gotoUserSetting(row){
        this.$router.push('/userinfo1')
      }
    }
  }
</script>

<style>
</style>


<style lang="less" scoped>
  .user-container {
    padding: 20px;
    position: relative;
  }
</style>
